import {Injectable} from '@nestjs/common';
import {InjectModel} from "nestjs-typegoose";
import {Action} from "@libs/db/models/action.model";
import {Model} from "mongoose";
import {getStatusDto} from "./dto/get-status.dto";
import {getListsDto} from "./dto/get-lists.dto";
import {createBrowseDto} from "./dto/create-browse.dto";
import {JwtService} from "@nestjs/jwt";

@Injectable()
export class ActionsService {
  constructor(@InjectModel(Action) private readonly actionModel: Model<Action>,
              private readonly jwtService: JwtService
  ) {
  }

  // 获取状态
  async getStatus(query: getStatusDto, user) {
    query.user = user.id
    const count = await this.actionModel.countDocuments(query)
    return {
      status: count > 0
    }
  }

  // 切换状态
  async toggleStatus(body: getStatusDto, user) {
    const res = await this.getStatus(body, user)
    body.user = user.id
    if (res.status) {
      await this.actionModel.deleteMany(body)
    } else {
      await this.actionModel.create(body)
    }
    return await this.getStatus(body, user)
  }

  // 获取正确状态列表
  async getList(query: string, user?) {
    const data = JSON.parse(query) as getListsDto
    if (!data.where.forbiddenUser) {
      data.where.user = user._id
    }
    const lists = await this.actionModel.find().setOptions(data);
    return lists.filter(item => item.object).map(item => item.object)
  }

  // 增加浏览量
  async createBrowse(body: createBrowseDto, auth: string) {
    if (auth) {
      const scret = auth.split(' ').pop()
      const token = await this.jwtService.verifyAsync(scret)
      body.user = token.id
    }
    return await this.actionModel.create(body)
  }
}
